﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Medianamik.Core
{
    /// <summary>
    /// Cette classe représente une relation ManyToMany entre deux types
    /// Une relation ManyToMany est en réalité la combinaison de deux relations OneToMany
    /// La relation se lit de gauche à droite.
    /// <example>Pour représenter les Groups associés à un User :
    /// User est le PrimaryType de LeftRelation
    /// Group est le PrimaryType de RightRelation
    /// UsersInGroups est le ForeignType de LeftRelation et RightRelation
    /// </example>
    /// </summary>
    public class ManyToManyRelation 
    {

        #region .ctors

        public ManyToManyRelation(OneToManyRelation pLeftRelation, OneToManyRelation pRightRelation)
        {
            if (pLeftRelation == null)
            {
                throw new ArgumentNullException("pLeftRelation","Relations cannot be null");
            }
            if (pRightRelation == null)
            {
                throw new ArgumentNullException("pRightRelation", "Relations cannot be null");
            }
            if (!pLeftRelation.ForeignTypeID.Equals(pRightRelation.ForeignTypeID))
            {
                throw new CoreException("Both relation must have the same ForeignTypeId");
            }
            if (pLeftRelation.PrimaryPropertyID.Equals(pRightRelation.ForeignPropertyID))
            {
                throw new CoreException("Relations must have diffrent ForeignPropertyId");
            }

            _leftRelation = pLeftRelation;
            _rightRelation = pRightRelation;
        }


        #endregion

        private OneToManyRelation _leftRelation;
        public OneToManyRelation LeftRelation
        {
            get
            {
                return _leftRelation; 
            }
        }

        private OneToManyRelation _rightRelation;
        public OneToManyRelation RightRelation
        {
            get
            {
                return _rightRelation;
            }
        }

        #region Methods

        

        #endregion



    }

	public class ManyToManyRelationEqualityComparer : IEqualityComparer<ManyToManyRelation>
	{
		#region IEqualityComparer<ManyToManyRelation> Members

		public bool Equals(ManyToManyRelation x, ManyToManyRelation y)
		{
			return GetHashCode(x).CompareTo(GetHashCode(y)) ==  0;
		}

		public int GetHashCode(ManyToManyRelation obj)
		{
			int hash = obj.LeftRelation.PrimaryPropertyID.GetHashCode()
				^ obj.LeftRelation.ForeignPropertyID.GetHashCode()
				^ obj.RightRelation.PrimaryPropertyID.GetHashCode()
				^ obj.RightRelation.ForeignPropertyID.GetHashCode();

            return hash;
		}

		#endregion
	}
}
